var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var signCode = "slel3@lsl334xx,deka";
var Cio = require('socket.io-client')
var log = require("./../util/loginfo").getInstand;
var gameConfig = require('./config/gameConfig');
var gameInfo = require('./class/game').getInstand;
gameInfo.init(gameConfig);
var Csocket = Cio('http://localhost:13000');

var roomMgr = require('./class/roommgr');
var userMgr = require('./class/usermgr');

Csocket.on('disconnect', function (data) {
    log.info("登录服务器被断开");
});

Csocket.on('connected', function (msg) {
    log.info("与登录服务器进行连接......");
    var info = {serverName: gameConfig.gameName, serverId: gameConfig.serverId, signCode: gameConfig.LoginServeSign}
    Csocket.emit('GameServerConnect', info);
});

Csocket.on('GameServerConnectResult', function (msg) {
    if (msg.resultCode) {
        log.info("连接成功");
    }
});

Csocket.on('LoginGameResult', function (msg) {
    try {
        if (!msg) {
            return;
        }
        log.info(".登录" + gameConfig.gameName + "服务器回应" + JSON.stringify(msg));
        if (msg.ResultCode) {
            gameInfo.updateUser(msg.userInfo);
        } else {
            gameInfo.deleteUserById(msg.userid, msg.msg);
        }
    } catch (error) {
        log.err(error);
    }
});

Csocket.on('addgold', function (msg) {
    try {
        if (!msg) {
            return;
        }
        //log.info(msg);
        var result = gameInfo.addgold(msg.userid, msg.addgold);
        Csocket.emit('addgoldResult', {Result: result});
    
        //当前用户桌子广播
        var User = gameInfo.getUser(msg.userid);
        if (User) {
            var tablestring = "table" + User.getTable();
            io.sockets.in(tablestring).emit('userGoldUpdate', {userId: msg.userid, updateSocre: User.getScore()});
        }
    } catch (error) {
        log.err(error);
    }
});

Csocket.on('getgold', function (msg) {
    try {
        if (!msg) {
            return;
        }
    
        var score = gameInfo.getPlayerScore(msg.userid);
        Csocket.emit('getgoldResult', {Result: 1, score: score});
    } catch (error) {
        log.err(error);
    }
});

Csocket.on('disconnectUser', function (msg) {
    try {
        var list = gameInfo.getOnlinePlayer();
        if (list[msg.userId]) {
            // kicked, ZZZ-20230509
            list[msg.userId]._socket.emit(msg.sysCommand, msg);
            list[msg.userId]._socket.disconnect();
        } else {
            log.info("用户不存在");
            var result = {ResultCode: 0, userId: msg.userId};
            Csocket.emit("userDisconnect", result);
        }
    } catch (error) {
        log.err(error);
    }
});


Csocket.on('applyMatchResult', function (_info) {
    try {
        //log.info(_info);
        gameInfo.addRankUserList(_info);
        //gameInfo.fishShoot(socket,fishShootInfo);
    } catch (error) {
        log.err(error);
    }
});


Csocket.on('Setmaintain', function () {
    try {
        gameInfo.Setmaintain();
    } catch (error) {
        log.err(error);
    }
});


gameInfo.setIo(io, Csocket);

io.on('connection', function (socket) {

    //log.info(socket + 'connected');
    socket.emit('connected', 'connect game server');


    //客户登录游戏
    socket.on('LoginGame', function (GameInfo) {
        try {
            var data = JSON.parse(GameInfo);
            GameInfo = data;
        } catch (e) {
            log.warn('LoginGame-json');
        }

        log.info("begin to check")
        //是不是维护模式
        if (gameInfo.isMaintain()) {
            log.info("维护模式,禁止登录!");
            socket.emit("maintain", {ResultCode: 1, msg: true});
            return;
        }

        log.info("check game info object")
        if (!GameInfo) {
            log.info("登录游戏,参数不正确!");
            return;
        }

        log.info("check game sign")
        if (GameInfo.sign) {
            if (!gameInfo.ApplyLogin(socket, GameInfo.userid)) {
                log.info("发奖期间,不允许登录")
                return;
            }
            log.info("prepare to add user")
            if (!gameInfo.getUser(GameInfo.userid)) {
                log.info("can add user")
                gameInfo.addUser(GameInfo, socket);
                var msg = {
                    userid: GameInfo.userid,
                    sign: GameInfo.sign,
                    gameId: gameInfo.serverId,
                    serverSign: signCode,
                    serverId: gameConfig.serverId
                };
                Csocket.emit('LoginGame', msg);
                //log.info("test4.发送新用户登录完成,让登录服务器删除用户")
            } else {
                log.info("用户已经在服务器了，无需重复登录");
            }
        }

    })

    //然后再登录房间
    socket.on('LoginRoom', function (RoomInfo) {
        try {
            var data = JSON.parse(RoomInfo);
            RoomInfo = data;
        } catch (e) {
            log.warn('LoginRoom-json');
        }

        //如果没有房间概念，就默认为1
        //这还应该检测是否进入了游戏，如果没有需要先进入
        //log.info("进入房间")
        gameInfo.LoginRoom(socket.userId, RoomInfo.roomid, socket);
    })


    //准备
    socket.on('ready', function (data) {

        var userId = socket.userId;
        if (userId == null) {
            return;
        }
        socket.gameMgr.setReady(userId);
        userMgr.broacastInRoom('user_ready_push', {
            userid: userId,
            ready: true
        }, userId, true);
    });

    //让牌
    socket.on('rangpai', function (data) {
        var userId = socket.userId;
        socket.gameMgr.userOps(userId, 'doGuo');
    });

    //弃牌
    socket.on('qipai', function (data) {
        var userId = socket.userId;
        socket.gameMgr.userOps(userId, 'doQuit');
    });

    //跟注
    socket.on('genpai', function (data) {
        var userId = socket.userId;
        socket.gameMgr.userOps(userId, 'doGen');
    });

    //加注
    socket.on('jiazhu', function (data) {
        var userId = socket.userId;
        socket.gameMgr.userOps(userId, 'doAdd', data);
    });

    //离开房间
    socket.on('LogoutRoom', function (data) {
        log.info("LogoutRoom")
        //退出
        var userId = socket.userId;
        var roomId = roomMgr.getUserRoom(userId);
        var onlineP = false;
        var roomInfo = roomMgr.getRoom(roomId);
        var waitingUsers = roomInfo.waitingUsers;
        var qipailist = roomInfo.qipailist;
        var is_waitingUsers = false;
        var is_qipai = false;

        if (waitingUsers.length > 0) {
            for (var rwu in waitingUsers) {
                if (waitingUsers[rwu].userid == userId) {
                    is_waitingUsers = true;
                    break
                }
            }
        }
        if (qipailist) {
            if (qipailist.indexOf(userId) > -1) {
                is_qipai = true
            }
        }

        // log.info("LogoutRoom---------------------------------------")
        // log.info(roomInfo.is_start);
        // log.info(is_waitingUsers);
        // log.info(is_qipai);
        // log.info(qipailist);


        if (roomInfo.is_start && !is_waitingUsers && !is_qipai) {
            onlineP = true
        }
        log.info("----------------------");
        log.info(onlineP);
        if (onlineP) {
            log.info("不让退出------------------------")
            socket.emit("noExit", true);
            return
        } else {
            userMgr.exitRoom(userId);
            socket.disconnect(1)
        }

    });
    socket.on('isUserInGame', function (data) {
        var userId = socket.userId;
        socket.gameMgr.isUserInGame(userId);
    });
    //获得用户筹码
    socket.on('getUserHolds', function (data) {
        var userId = socket.userId;
        var data = socket.gameMgr.getUserHolds(userId);
        socket.emit('socket_MyHolds', data);
    });
    //根据用户ID获得用户信息
    socket.on('getUserInfoByUserid', function (data) {
        var userId = socket.userId;
        socket.gameMgr.getUserInfoByUserid(userId);
    });
    //根据用户ID获得游戏信息
    socket.on('getGameInfoByUserid', function (data) {
        var userId = socket.userId;
        socket.gameMgr.getGameInfoByUserid(userId);
    });
    //断开链接
    socket.on('disconnect', function (data) {
        log.info('断开连接============================');
        log.info(data);
        var userId = socket.userId;
        if (!userId) {
            return;
        }
        var userInfo = gameInfo.getUser(userId);
        if (userInfo) {
            if (userInfo.Islogin()) {
                // roomMgr.exitRoom(userId)
                gameInfo.deleteUser(socket,data);

                var result = {
                    ResultCode: 1,
                    userId: userInfo._userId,
                    userScore: userInfo._score,
                    gameId: gameConfig.serverId,
                    nolog: true
                };
                Csocket.emit("userDisconnect", result);
                log.info("userDisconnect userid " + userInfo._userId + " socket disconnect!!!!!!!!!");
                //断线存储相应数据(在新的数据库里存储,消耗子弹与收获金币)
                socket.userId = null;
            } else {
                userInfo._isLeave = true;
                log.warn('未更新用户数据离开');
            }
        } else {
            log.info("用户未登录离开!")
        }


        //通知房间内其它玩家
        userMgr.broacastInRoom('user_state_push', data, userId);
        //清除玩家的在线信息
        // userMgr.del(userId);
        socket.userId = null;
    });

    socket.on('game_ping', function (data) {
        var userId = socket.userId;
        if (!userId) {
            return;
        }
        socket.emit('game_pong');
    });
});


app.set('port', process.env.PORT || gameConfig.port);

var server = http.listen(app.get('port'), function () {
    log.info('start at port:' + server.address().port);
});


function jsonp(code) {
    try {
        var data = JSON.parse(code);
        return data;
    } catch (e) {
        log.warn(code);
        log.warn('解析json,出错!');
    }
}

log.info("德州扑克服务器启动");


